const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
const bodyParser = require('koa-bodyparser');
const marked=require('marked');
const path = require('path');
const documentPath='/target/';
var fs = require("fs");

//读取一个文件夹下的所有子文件夹和文件
function readFileList(dir, filesList = [],logicPath) {
  const files = fs.readdirSync(dir);
  files.forEach((item, index) => {
    var fullPath = path.join(dir, item);
    const stat = fs.statSync(fullPath);
    if (stat.isDirectory()) {
      let d={name:item,children:[],type:'dir',path:logicPath+'/'+item}
      filesList.push(d)
      readFileList(path.join(dir, item), d.children,logicPath+'/'+item); //递归读取文件
    } else {
      let f={name:item,type:'file',path:logicPath+'/'+item}
      filesList.push(f);           
    }    
  });
}
function loadMdContent(fullPath){
  return new Promise((resolve,reject)=>{
    fs.readFile(fullPath, 'utf8' , (err, data) => {
      if (err) {
        console.error(err)
        reject(err);
      }
      resolve(data);
    })
  })
  
}

app.use(async (ctx,next) => {
    console.log('收到请求:'+ctx.request.path)
    await next();
  });
  app.use(bodyParser());

// 指定一个url匹配
router.get('/', async (ctx) => {
  ctx.type = 'html';
  ctx.body = '<h1>index!</h1>';
})
router.get('/getAllTree', async (ctx) => {
  ctx.type = 'json';
  
  //扫描target目录，返回所有的目录，树型结构返回
  let f=[];
  readFileList(path.resolve(__dirname, 'target'),f,'');
  ctx.body = f;
})
router.post('/loadmd', async (ctx) => {
  ctx.type = 'text';
  ctx.body = '# Hello markdown!';
  const body=ctx.request.body;
  const filePath=body.path;
  const fullPath=path.join(__dirname, documentPath,filePath);
  const content=await loadMdContent(fullPath)
  
  ctx.body=content;
  
})
app.use(router.routes());

app.listen(30000);
console.log('服务启动成功，开始监听30000端口');